import time
import configs
import torch
import sounddevice as sd
from template.singleton import Singleton
from utils import service_functions


class New_Speak:
    def __init__(self) -> None:
        self.__check_internet_speak()
        try:
            self.settings()
        except BaseException:
            configs.settings["type_sintez"] = ""

    def settings(
        self, language="ru", model_id="ru_v3", sample_rate=48000, speaker="baya"
    ):
        self.sample_rate = sample_rate
        self.speaker = speaker
        self.put_accent = True
        self.put_yoo = True
        self.device = torch.device("cpu")  # cpu или дри
        self.model, example_text = torch.hub.load(
            repo_or_dir="snakers4/silero-models",
            model="silero_tts",
            language=language,
            speaker=model_id,
        )
        self.model.to(self.device)

    def speak(self, _say: str, lang: str = "defult") -> None:
        # print(_say, "ffkkkkf")
        audio = self.model.apply_tts(
            text=_say,
            speaker=self.speaker,
            sample_rate=self.sample_rate,
            put_accent=self.put_accent,
            put_yo=self.put_yoo,
        )
        sd.play(audio, self.sample_rate)
        time.sleep(len(audio) / self.sample_rate)
        sd.stop()

    def __check_internet_speak(self):
        net_boll = service_functions.check_internet()
        if net_boll and configs.settings["type_sintez"] == "new":
            configs.settings["type_sintez"] = "new"
        else:
            configs.settings["type_sintez"] = ""
